package com.kgc.test;

import java.sql.*;

public class MySQLConnector {
    public static void main(String[] args) {
        // 数据库URL，格式为 jdbc:mysql://hostname:port/databaseName
        String url = "jdbc:mysql://39.101.169.139:3306/db_blog?useSSL=false&allowPublicKeyRetrieval=true";
        // 数据库用户名
        String user = "root";
        // 数据库密码
        String password = "love1225";

        try {
            // 加载并注册JDBC驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            Connection conn = DriverManager.getConnection(url, user, password);
            System.out.println("连接成功！");
            // 操作数据库...
            String sql = "select * from users";
            PreparedStatement pre = conn.prepareStatement(sql);
            ResultSet resultSet = pre.executeQuery();
            while (resultSet.next()) {
                String name = resultSet.getString("username");
                System.out.println(name);
            }
            // 关闭连接
            conn.close();
        } catch (ClassNotFoundException e) {
            System.out.println("JDBC驱动未找到！");
        } catch (SQLException e) {
            System.out.println("数据库连接失败：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}